package com.freak.freakmusic.net.factory

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 *
 * @author freak
 * @date 2019/03/12
 */

class CustomConverterFactory private constructor(private val gson: Gson) : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type?, annotations: Array<Annotation>?,
        retrofit: Retrofit?
    ): Converter<ResponseBody, *>? {
        val adapter = gson.getAdapter(TypeToken.get(type!!))
        return CustomResponseBodyConverter(gson, adapter)
    }

    override fun requestBodyConverter(
        type: Type?,
        parameterAnnotations: Array<Annotation>?,
        methodAnnotations: Array<Annotation>?,
        retrofit: Retrofit?
    ): Converter<*, RequestBody>? {
        val adapter = gson.getAdapter(TypeToken.get(type!!))
        return CustomRequestBodyConverter(gson, adapter)
    }

    companion object {

        /**
         * Create an instance using a default [Gson] instance for conversion. Encoding to JSON and
         * decoding from JSON (when no charset is specified by a header) will use UTF-8.
         */
        fun create(): CustomConverterFactory {
            //        return create(new Gson());
            return create(
                GsonBuilder().serializeNulls().disableHtmlEscaping().registerTypeAdapterFactory(
                    NullStringToEmptyAdapterFactory<Any>()
                ).create()
            )
        }

        /**
         * Create an instance using `gson` for conversion. Encoding to JSON and
         * decoding from JSON (when no charset is specified by a header) will use UTF-8.
         *
         * Guarding public API nullability.
         */
        fun create(gson: Gson?): CustomConverterFactory {
            if (gson == null) {
                throw NullPointerException("gson == null")
            }
            return CustomConverterFactory(gson)
        }
    }


}
